package com.example.wearing.tools;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {
    private static final String TAG = "NetUtil";
    public static final String URL_WEATHER_WITH_FUTURE = "https://www.yiketianqi.com/free/day?appid=74555114&appsecret=Jb6j4Nan&unescape=1";
    public static final String URL_WEATHER_WITH_FUTURE2 = "https://yiketianqi.com/api?unescape=1&version=v6&appid=74555114&appsecret=Jb6j4Nan";

    public static String doGet(String urlStr){
        String result = "";
        HttpURLConnection connection = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        //连接网络
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);

            //从连接中读取数据（二进制）
            InputStream inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            //二进制流送去缓冲区
            bufferedReader = new BufferedReader(inputStreamReader);
            //从缓存区中一行行读取字符串
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            result = stringBuilder.toString();

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(connection != null){
                connection.disconnect();
            }

            if(inputStreamReader != null){
                try{
                    inputStreamReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(bufferedReader != null){
                try{
                    bufferedReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String getWeatherOfCity(String city){
        //拼接处获取天气的url
        //https://www.yiketianqi.com/free/day?appid=74555114&appsecret=Jb6j4Nan&unescape=1
        String weatherUrl = URL_WEATHER_WITH_FUTURE2 + "&city=" + city;
        Log.i(TAG, "getWeatherOfCity: "+city);
        Log.i(TAG, "getWeatherOfCity: weatherUrl---"+weatherUrl);
        String weatherResult = doGet(weatherUrl);
        Log.i(TAG, "getWeatherOfCity: weatherResult---"+weatherResult);
        return weatherResult;
    }

}
